using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.WriteAPI.Applications.Commands.Users;
using MediatR;

namespace B.S.BaseData.WriteAPI.Applications.Handlers.Users
{
    /// <summary>
    /// 修改用户处理器
    /// </summary>
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ApiResult>
    {
        private readonly IUserRepository _userRep;
        private readonly ILogger<UpdateUserHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public UpdateUserHandler(IUserRepository userRep, ILogger<UpdateUserHandler> logger)
        {
            this._userRep = userRep;
            this._logger = logger;
        }

        /// <summary>
        /// 处理修改用户命令
        /// </summary>
        public async Task<ApiResult> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var dto = request.UserDto;

                // 获取用户信息
                var user = await _userRep.GetByIdAsync(dto.UserId);
                if (user == null)
                {
                    return ApiResult.Fail("用户不存在", StatusCodeEnum.Fail);
                }

                // 更新用户信息
                if (!string.IsNullOrEmpty(dto.Phone))
                    user.Phone = dto.Phone;

                if (!string.IsNullOrEmpty(dto.MembershipLevel))
                    user.MembershipLevel = dto.MembershipLevel;

                if (!string.IsNullOrEmpty(dto.Gender))
                    user.Gender = dto.Gender;

                if (!string.IsNullOrEmpty(dto.MembershipLevel))
                    user.MembershipLevel = dto.MembershipLevel;

                if (dto.Birthday!=null)
                    user.Birthday = dto.Birthday;

                if (!string.IsNullOrEmpty(dto.City))
                    user.City = dto.City;

                if (!string.IsNullOrEmpty(dto.Occupation))
                    user.Occupation = dto.Occupation;

                if (!string.IsNullOrEmpty(dto.PersonalSignature))
                    user.PersonalSignature = dto.PersonalSignature;



                // 保存到数据库
                await _userRep.UpdateAsync(user);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改用户信息失败");
                return ApiResult.Fail("修改用户信息失败", StatusCodeEnum.Exception);
            }
        }
    }
}